    //
//  ConversionViewController.m
//  DSNDialer
//
//  Created by Chris Morrell on 4/30/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ConversionViewController.h"
#import "ConversionDetailViewController.h"
#import "DirectoryTableViewController.h"
#import "SplashViewController.h"
#import "RecentConversionsTableViewController.h"

@implementation ConversionViewController
@synthesize phoneNumberField;
@synthesize convertButton;
@synthesize recentButton;
@synthesize dsnDirectoryButton;
@synthesize dsnCommercialChooser;
@synthesize recentArray;
@synthesize infoButton;

- (void)viewDidLoad {
    [super viewDidLoad];
	self.view.backgroundColor = [UIColor clearColor];
	
	self.dsnCommercialChooser.tintColor = [UIColor grayColor];
	
	UIImage *buttonImageNormal = [UIImage imageNamed:@"test-gradient.png"];
	UIImage *stretchableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
	UIImage *buttonImagePressed = [UIImage imageNamed:@"test-gradient2.png"];
	UIImage *stretchableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];

	[convertButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
	[convertButton setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];
	[convertButton setAlpha:0.85];

	[dsnDirectoryButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
	[dsnDirectoryButton setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];
	[dsnDirectoryButton setAlpha:0.85];
	
	[recentButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
	[recentButton setBackgroundImage:stretchableButtonImagePressed forState:UIControlStateHighlighted];
	[recentButton setAlpha:0.85];

	[phoneNumberField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
 	[phoneNumberField becomeFirstResponder];

	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *DataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Recents.plist"];

	NSString *errorDesc = nil;
	NSPropertyListFormat format;
	NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:DataPath];

	NSMutableArray *thisArray = (NSMutableArray *)[NSPropertyListSerialization
												   propertyListFromData:plistXML
												   mutabilityOption:NSPropertyListMutableContainersAndLeaves
												   format:&format errorDescription:&errorDesc];
	if (!thisArray) 
	{
		NSLog(@"%@",errorDesc);
	}
	[errorDesc release];
	
	self.recentArray = thisArray;
	[recentArray retain];
	[thisArray release];
	
}

-(PhoneBookEntry *)convertThisNumber:(NSString *)number fromDSN:(BOOL)fromDSN
{
	PhoneBookEntry *thisEntry = [[[PhoneBookEntry alloc] init] autorelease];
	NSString *errorDesc = nil;
	NSPropertyListFormat format;
	NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Conversion" ofType:@"plist"];
	NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
	NSArray *phoneConversionArray = (NSArray *)[NSPropertyListSerialization
											 propertyListFromData:plistXML
											 mutabilityOption:NSPropertyListMutableContainersAndLeaves
											 format:&format errorDescription:&errorDesc];
	if (!phoneConversionArray) 
	{
		NSLog(@"%@",errorDesc);
	}
	[errorDesc release];
	
	NSString *numberToConvert = [NSString stringWithFormat:@"%@",number];
	NSString *numberToCompare = [[[NSString alloc] init] autorelease];
	NSString *convertedNumber = [[[NSString alloc] init] autorelease];
	numberToConvert = [numberToConvert stringByReplacingOccurrencesOfString:@"(" withString:@""];
	numberToConvert = [numberToConvert stringByReplacingOccurrencesOfString:@")" withString:@""];
	numberToConvert = [numberToConvert stringByReplacingOccurrencesOfString:@"-" withString:@""];
	numberToConvert = [numberToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""];
	
	for(NSDictionary *entry in phoneConversionArray)
	{
		if (fromDSN)
		{
			numberToCompare = [entry objectForKey:@"dsn"];
			convertedNumber = [entry objectForKey:@"comm"];
		}
		else
		{
			numberToCompare = [entry objectForKey:@"comm"];
			convertedNumber = [entry objectForKey:@"dsn"];
		}
	
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@"(" withString:@""];
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@")" withString:@""];
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@"-" withString:@""];
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@"#" withString:@""];
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@"x" withString:@""];
		numberToCompare = [numberToCompare stringByReplacingOccurrencesOfString:@"X" withString:@""];
		
		if ([numberToCompare isEqualToString:[numberToConvert substringToIndex:[numberToCompare length]]])
		{
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@"x" withString:@""];
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@"X" withString:@""];
			convertedNumber = [convertedNumber stringByReplacingOccurrencesOfString:@"#" withString:@""];
			
			if (fromDSN)
			{
				thisEntry.dsn = number;
				thisEntry.comm = [self formatPhoneNumber:[NSString stringWithFormat:@"%@%@",convertedNumber,[numberToConvert substringFromIndex:[numberToCompare length]]]];
			}
			else 
			{
				thisEntry.comm = number;
				thisEntry.dsn = [self formatPhoneNumber:[NSString stringWithFormat:@"%@%@",convertedNumber,[numberToConvert substringFromIndex:[numberToCompare length]]]];
			}
//			[numberToCompare release];
//			[numberToConvert release];
			thisEntry.city = [entry objectForKey:@"city"];
			thisEntry.state = [entry objectForKey:@"state"];
			thisEntry.country = [entry objectForKey:@"country"];
			
			NSDictionary *newEntry = [[NSDictionary alloc] initWithObjectsAndKeys:
									  thisEntry.comm, @"comm",
									  thisEntry.dsn, @"dsn",
									  thisEntry.city, @"city",
									  thisEntry.state, @"state",
									  thisEntry.country, @"country",
									  thisEntry.sitename, @"sitename", nil];
			BOOL found = NO;
			for (NSDictionary *anEntry in recentArray)
			{
				if ([[newEntry objectForKey:@"dsn"] isEqualToString:[anEntry objectForKey:@"dsn"]])
					found = YES;
			}
			if (!found)	[recentArray insertObject:newEntry atIndex:0];
			
			if ([recentArray count] > 20) [recentArray removeLastObject];
			[newEntry release];
			NSString *errorDesc;
			NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			NSString *documentsDirectory = [paths objectAtIndex:0]; 
			NSString *DataPath = [documentsDirectory stringByAppendingPathComponent:@"Recents.plist"];
			
			NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:recentArray format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];

			if (plistData) {
				[plistData writeToFile:DataPath atomically:YES];
			}
			
			return thisEntry;
		}
	}
	return thisEntry;
#pragma unused(numberToCompare)
#pragma unused(convertedNumber)
#pragma unused(thisEntry)	
}

-(NSString *)formatPhoneNumber:(NSString *)unformattedNumber
{
	NSString *formattedNumber = @"";
	unformattedNumber = [unformattedNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
	unformattedNumber = [unformattedNumber stringByReplacingOccurrencesOfString:@")" withString:@""];
	unformattedNumber = [unformattedNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
	
	NSString *lastFour = @"";
	NSString *middleThree = @"";
	NSString *areaCode = @"";
	
	NSUInteger textLength = [unformattedNumber length];
	if (textLength <= 4)
	{
		lastFour = unformattedNumber;
		formattedNumber = [NSString stringWithFormat:@"%@",lastFour];
	}
	else if (textLength <= 7)
	{
		lastFour = [unformattedNumber substringFromIndex:textLength - 4];
		middleThree = [unformattedNumber substringToIndex:textLength - 4];
		formattedNumber = [NSString stringWithFormat:@"%@-%@",middleThree,lastFour];
	}
	else if (textLength <= 10)
	{
		lastFour = [unformattedNumber substringFromIndex:textLength - 4];
		NSRange newRange = NSMakeRange(textLength - 7, 3);
		middleThree = [unformattedNumber substringWithRange:newRange];
		areaCode = [unformattedNumber substringToIndex:textLength - 7];
		formattedNumber = [NSString stringWithFormat:@"(%@)%@-%@",areaCode,middleThree,lastFour];
	}
	return formattedNumber;
}

-(void)textFieldDidChange:(UITextField *)textField 
{
	static BOOL toggle = NO;
	if (toggle) {
		toggle = NO;
		return;
	}
	if ([textField.text length] > 13)
	{
		toggle = YES;
		textField.text = [textField.text substringToIndex:13];
		return;
	}
	toggle = YES;
	phoneNumberField.text = [self formatPhoneNumber:textField.text];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (alertView.numberOfButtons == 2 && buttonIndex == 0)
	{
		phoneNumberField.text = [NSString stringWithFormat:@"(312)%@",phoneNumberField.text];
		[self convertButtonAction:self];
	}
}


-(IBAction)convertButtonAction:(id)sender
{
	BOOL fromDSN = !dsnCommercialChooser.selectedSegmentIndex;
	if ([phoneNumberField.text length] < 8)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please enter a complete number to convert." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	else if (fromDSN && [phoneNumberField.text length] == 8)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CONUS DSN" message:@"If this number is CONUS, 312 should be the area code.  Is this a CONUS DSN number?" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No",nil];
		[alert show];
		[alert release];
		return;
	}
	else if (!fromDSN && [phoneNumberField.text length] <13)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Your commercial number should consist of 10 digits." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
		return;
	}
	ConversionDetailViewController *myConversionDetailViewController = [[ConversionDetailViewController alloc] initWithNibName:@"ConversionDetailView" bundle:nil];
	PhoneBookEntry *thisEntry = [[[PhoneBookEntry alloc] init] autorelease];

	thisEntry = [self convertThisNumber:phoneNumberField.text fromDSN:fromDSN];
	if (thisEntry.comm == NULL || thisEntry.dsn == NULL)
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@ cannot be converted at this time.  For conversion additions, contact the developer using the e-mail link at the bottom of the information screen.",phoneNumberField.text] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	else
	{
		myConversionDetailViewController.detailEntry = thisEntry;
		myConversionDetailViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
		myConversionDetailViewController.view.backgroundColor = [UIColor clearColor];

		[super presentModalViewController:myConversionDetailViewController animated:YES];
	}
	[myConversionDetailViewController release];
#pragma unused(thisEntry)
}

-(IBAction)recentButtonAction:(id)sender
{
	RecentConversionsTableViewController *myRecentConversionsTableViewController = [[RecentConversionsTableViewController alloc] initWithStyle:UITableViewStylePlain];
	myRecentConversionsTableViewController.title = @"Recent";
	myRecentConversionsTableViewController.recentArray = recentArray;
	myRecentConversionsTableViewController.view.backgroundColor = [UIColor clearColor];
		
	UINavigationController *myRecentConversionsNavigationController = [[UINavigationController alloc] initWithRootViewController:myRecentConversionsTableViewController];
	[myRecentConversionsTableViewController release];

	myRecentConversionsNavigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	myRecentConversionsNavigationController.view.backgroundColor = [UIColor clearColor];
	myRecentConversionsNavigationController.navigationBar.tintColor = [UIColor grayColor];

	[super presentModalViewController:myRecentConversionsNavigationController animated:YES];
	[myRecentConversionsNavigationController release];
}

-(IBAction)dsnDirectoryButtonAction:(id)sender
{	
	DirectoryTableViewController *myDirectoryTableViewController = [[DirectoryTableViewController alloc] initWithStyle:UITableViewStylePlain];
	myDirectoryTableViewController.title = @"Operator Directory";
	myDirectoryTableViewController.view.backgroundColor = [UIColor clearColor];

	UINavigationController *myDirectoryNavigationController = [[[UINavigationController alloc] initWithRootViewController:myDirectoryTableViewController] autorelease];
	[myDirectoryTableViewController release];
	myDirectoryNavigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	myDirectoryNavigationController.navigationBar.tintColor = [UIColor grayColor];
	myDirectoryNavigationController.view.backgroundColor = [UIColor clearColor];

	[super presentModalViewController:myDirectoryNavigationController animated:YES];
}

-(IBAction)infoButtonAction:(id)sender
{
	SplashViewController *mySplashViewController = [[SplashViewController alloc] initWithNibName:@"SplashView" bundle:nil];
	mySplashViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	mySplashViewController.emailButton.enabled = YES;
	[self presentModalViewController:mySplashViewController animated:YES];
}

-(void)showSplash
{
	SplashViewController *mySplashViewController = [[SplashViewController alloc] initWithNibName:@"SplashView" bundle:nil];
	mySplashViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
	[self presentModalViewController:mySplashViewController animated:NO];
	mySplashViewController.emailButton.enabled = NO;
	mySplashViewController.emailButton.titleLabel.textColor = [UIColor blackColor];
//	mySplashViewController.emailButton.hidden = YES;
	[self performSelector:@selector(hideSplash) withObject:nil afterDelay:3.0];
}

-(void)hideSplash
{
	[[self modalViewController] dismissModalViewControllerAnimated:YES];
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.phoneNumberField = nil;
	self.convertButton = nil;
	self.recentButton = nil;
	self.dsnDirectoryButton = nil;
	self.dsnCommercialChooser = nil;
	self.infoButton = nil;
}


- (void)dealloc {
    [super dealloc];
	[phoneNumberField release];
	[convertButton release];
	[recentButton release];
	[dsnDirectoryButton release];
	[dsnCommercialChooser release];
	[infoButton release];
	[recentArray release];
}


@end
